package com.shanghaionstar.pin.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.onstar.cn.auth.AuthPinTokenEntity;
import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.login.service.AuthorService;
import com.shanghaionstar.pin.PinDialogFragment;
import com.shanghaionstar.pin.model.PinModel;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/6/30.
 */
public class PinPresenter extends BasePresenter {
    private AuthorService authorService;
    private LogManager log = LogManager.getInstance();
    private PinDialogFragment pinView;
    private Subscription upgradeSubscription;
    private Subscription reauthSubscription;

    private Context context;
    private RemoteCommandsType remoteCommandsType;

    public PinPresenter(IMVPScheduler mvpScheduler, Context context) {
        super(mvpScheduler);
        authorService = new AuthorService(context);
        this.context = context;
        super.setServiceProvider(authorService);
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        pinView = (PinDialogFragment) view;
    }

    public void sendPin(final PinModel pinModel) {
        String pin = pinModel.getPinCode();
        RemoteCommandsType inputRemoteCommandType = pinModel.getRemoteCommandsType();
        this.remoteCommandsType = inputRemoteCommandType;
        if (BusinessUtil.isAutoSendPin(remoteCommandsType,context)) {
            pinView.onReponseSuccess(remoteCommandsType);
        } else if (TextUtils.isEmpty(pin)) {
            pinView.onResponseError(new OnStarException("", context.getString(R.string.pin_format_error)));
        } else {
            pinView.setLoading(true);
            final AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
            entity.setPin(pin);
            if (BusinessUtil.checkTokenExpired(context)) {
                reauthPin(entity,pinModel);
            } else {
                upgradeSubscription = authorService.doUpgrade(entity)
                        .subscribeOn(mvpScheduler.backgroundThread())
                        .observeOn(mvpScheduler.mainThread())
                        .subscribe(new Action1<String>() {
                            @Override
                            public void call(String s) {
                                ApplicationUtil.getInstance().setPin( true);
                                pinView.onReponseSuccess(pinModel);
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                //里面抛出的Error信息
                                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, (HttpException)throwable);
                                pinView.onResponseError(new HttpException(errorInfo.getCode(),errorInfo.getMsg()));
                            }
                        });
            }
        }
    }

    private void reauthPin(AuthTokenRequestEntity entity,final PinModel pinModel) {
        reauthSubscription = authorService.pinReauth(entity).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<AuthPinTokenEntity>() {
                    @Override
                    public void call(AuthPinTokenEntity s) {
                        pinView.onReponseSuccess(pinModel);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, (HttpException) throwable);
                        pinView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
                    }
                });
    }

    @Override
    public void finish() {
        if (upgradeSubscription != null && !upgradeSubscription.isUnsubscribed()) {
            upgradeSubscription.unsubscribe();
        }
        if (reauthSubscription != null && !reauthSubscription.isUnsubscribed()) {
            reauthSubscription.unsubscribe();
        }
    }
}
